package svr

import (
	"gitee.com/yysf-xin/dproxy/pkg/db"
	"gitee.com/yysf-xin/dproxy/pkg/model"
	"gitee.com/yysf-xin/dproxy/pkg/rest"
	"gitee.com/yysf-xin/dproxy/pkg/tools"
	"net"
	"net/http"
	"sync"
)

type LocalServer struct {
	model.State
	Mux       *http.ServeMux
	Host      string
	MuxMap    map[*db.LocalServer]http.Handler
	LocalLock sync.RWMutex
	Srv       *http.Server
	Name      string
}

func (l *LocalServer) CustomFlag() uint8 {
	return rest.GET | rest.DELETE
}

func (l *LocalServer) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
	l.Mux.ServeHTTP(writer, request)
}

func (l *LocalServer) ChangeStatus(status bool) {
}

func (l *LocalServer) String() string {
	return l.Name
}

func (l *LocalServer) InitMux() {
	mux := http.NewServeMux()
	for server := range l.MuxMap {
		mux.Handle(server.Path, l.MuxMap[server])
	}
	l.Mux = mux
}

func (l *LocalServer) Start() (err error) {
	tools.Log.Println("start", l)
	l.Srv = &http.Server{
		Addr:    l.Host,
		Handler: l,
	}
	ln, err := net.Listen("tcp", l.Srv.Addr)
	if err == nil {
		go func() {
			l.Status = 1
			e := l.Srv.Serve(ln)
			if e != nil {
				tools.Log.Println(l.Host, "err", e)
			}
		}()
	}
	return err

}

func (l *LocalServer) Stop() {
	if l.Srv != nil {
		err := l.Srv.Close()
		if err != nil && err != http.ErrServerClosed {
			tools.Log.Println(l.Host, "stop err", err)
		}
		l.Status = 0
	}
	tools.Log.Println("stopped", l)
}
